#!/usr/bin/env python
# -*- coding: utf-8 -*-

from datetime import timedelta
import zmq
import hashlib
from common.config import ServiceConfig
from web_server.mock.user_mgr import UserMgr
from web_server.mock.project_mgr import ProjectMgr

class HttpService:
    """代理服务类，作为Web后端API和反向代理服务器"""
    
    def __init__(self, app, session, socketio):
        """初始化代理服务"""
        self.app = app
        self.session = session
        self.socketio = socketio        
        self.user_mgr = UserMgr(app, session)
        self.project_mgr = ProjectMgr(app, session)
        # self.host = ServiceConfig.PROXY_SERVICE_HOST
        # self.port = ServiceConfig.PROXY_SERVICE_PORT
        # self.device_service_host = ServiceConfig.DEVICE_SERVICE_HOST
        # self.device_service_port = ServiceConfig.DEVICE_SERVICE_ZMQ_PORT
        # self.resource_service_host = ServiceConfig.RESOURCE_SERVICE_HOST
        # self.resource_service_port = ServiceConfig.RESOURCE_SERVICE_PORT
        # self.zmq_context = zmq.Context()
        # self.zmq_socket = None
    
    def destroy(self):
        if self.user_mgr:
            self.user_mgr.destroy()
            self.user_mgr = None
        self.socketio = None
        self.session = None
        self.app = None

    def __del__(self):
        """销毁代理服务"""
        self.destroy()

    def start(self):
        """启动代理服务"""
        app = self.app
        socketio = self.socketio
        try:
            self.app.logger.info(f'正在启动HTTP服务，主机: {app.config['HOST']}, 端口: {app.config['PORT']}')
            # Run the Flask app with SocketIO
            socketio.run(
                    app,
                    host=app.config['HOST'],
                    port=app.config['PORT'],
                    debug=app.config['DEBUG'],
                    use_reloader=app.config['USE_RELOADER'])
        finally:
            self.destroy()    
            app.logger.info('HTTP服务已停止')
    

    def login(self, username, password, remember):
        user = None
        if username not in self.user_mgr.users:
            return False
        hashed_password = hashlib.md5(password.encode()).hexdigest()
        if self.user_mgr.users[username]['password'] != hashed_password:
            return False
        user = self.user_mgr.users[username]
        # 登录成功，设置会话
        self.session['username'] = username
        self.session['name'] = user['name']
        self.session['role'] = user['role']
        # 如果选择了"记住我"，设置会话过期时间为30天
        if remember:
            self.session.permanent = True
            self.app.permanent_session_lifetime = timedelta(days=30)
        return True

    def logout(self):
        self.session.clear()

    def call_project_api(self, api:str, args: dict) -> dict:
        project_api = self.project_mgr.apis.get(api, None)
        if project_api is None:
            return {
                'code': 500, 
                'content': {
                    'message': f'project api: {api} not supported in mock mode'
                }
            }
        return project_api(**args)
